import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Search from '@/views/search'
import SearchResult from '@/views/search/result.vue'
import Article from '@/views/article'
import Edit from '@/views/layout/user/edit.vue'
import Chat from '@/views/layout/user/chat.vue'

// 导入二级路由
import Home from '@/views/layout/home'
import QA from '@/views/layout/qa'
import Video from '@/views/layout/video'
import User from '@/views/layout/user'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home,
        meta: {
          isKeepLive: true
        }
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/',
    component: Layout
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫
// 需要拦截的页面(需要登录才可以访问到)
const loginURL = ['/user', '/qa', '/user/edit']

router.beforeEach(function(to, from, next) {
  // console.log('从哪来的form', from)
  // console.log('去哪里to', to)
  const token = store.state.user.token.token
  // console.log(token)

  if (token) {
    next()
  } else {
    // 没有token
    if (loginURL.some(item => to.path === item)) {
      // if成立，需要登录
      // next('/login') // 提示，导航跳转到/user 失败了，跳转到了/login
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})
export default router
